package org.project.d.network.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;
import org.project.d.network.protocol.Packet;

/**
 * @author lin
 * @version V1.0
 * @description
 * @date 2020/6/11 4:42 下午
 */
public class PacketDecoder extends LengthFieldBasedFrameDecoder {


    public PacketDecoder() {
        super(Packet.packetMaxLength, Packet.lengthFieldOffset, Packet.lengthFieldLength);
    }


    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf byteBuf = (ByteBuf) super.decode(ctx, in);
        if (byteBuf == null) {
            return null;
        }
        try {
            return Packet.decodePacket(byteBuf);
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }
    }
}
